<template>
  <div class='container'>

    <el-card>
       <div slot="header">{{$route.query.id?'试题修改':'试题录入'}}</div>
      <el-form ref="form" label-width="80px" label-position="left" :model="allForm" :rules="allRules">
        <!--1、 学科 -->
         <el-form-item label="学科：" prop="subjectID">
          <el-select @change="changeSubject" v-model="allForm.subjectID" placeholder="请选择" style="width:45%">
          <el-option
            v-for="item in subjectsOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        </el-form-item>
        <!--2、 目录 -->
         <el-form-item label="目录：" prop="creatorID">
           <el-select v-model="allForm.creatorID" placeholder="请选择" style="width:45%" >
          <el-option
            v-for="item in directorysOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        </el-form-item>
        <!--3、 企业 -->
         <el-form-item label="企业：" prop="id">
            <el-select v-model="allForm.id" placeholder="请选择" style="width:45%">
          <el-option
            v-for="item in companysOptions"
            :key="item.id"
            :label="item.label"
            :value="item.company">
          </el-option>
        </el-select>
        </el-form-item>

        <!--4、 城市 provincesId-->
         <el-form-item label="城市：" prop="city">
          <el-select
          v-model="allForm.provinces"
          style="width:22%;margin-right:8px"
          @change="getAreaOptions"
          >
             <el-option
            v-for="item in provincesOptions"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
          </el-select>
          <el-select v-model="allForm.city" style="width:22%" >
            <el-option
            v-for="item in areaOptions"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
          </el-select>
        </el-form-item>

        <!--5、 方向 -->
        <el-form-item label="方向："  prop="direction">
          <el-select v-model="allForm.direction" placeholder="请选择" style="width:45%">
          <el-option
            v-for="item in directionOptions"
            :key="item"
            :label="item"
            :value="item">
          </el-option>
          </el-select>
        </el-form-item>
        <!--6、 题型部分 -->
        <el-form-item label="题型：" prop="questionType">
          <el-radio-group @change="changeRadio({})" v-model="allForm.questionType">
              <el-radio v-for="item in questionType" :key="item.value" :label="item.value+''">{{item.label}}</el-radio>
           </el-radio-group>
        </el-form-item>
        <!--7、 难度部分 -->
        <el-form-item label="难度：" prop="difficulty">
           <el-radio-group v-model="allForm.difficulty">
              <el-radio v-for="item in difficulty" :key="item.value" :label="item.value+''">{{item.label}}</el-radio>
           </el-radio-group>
        </el-form-item>
        <!--8、 题干部分-富文本框 -->
        <el-form-item label="题干：" prop="question">
           <quill-editor @blur="checkQustion" v-model="allForm.question" :options="editorOptions"></quill-editor>
        </el-form-item>
        <!--9、 选项部分 -->
        <el-form-item label="选项：" prop="options" v-if="allForm.questionType!=='3'">
         <div class="option_item"  v-for="item in allForm.options" :key="item.code">
          <el-radio v-if="allForm.questionType==='1'" @change="changeRadio(item)" style="margin-top:26px" v-model="item.isRight" :label="true">{{item.code}}：</el-radio>
          <el-checkbox v-if="allForm.questionType==='2'" v-model="item.isRight" style="margin-right:10px;margin-top:11px;" :label="true">{{item.code}}：</el-checkbox>
          <el-input  v-model="item.title" style="width:25%;margin-top:13px;"></el-input>
          <el-upload
          action="https://jsonplaceholder.typicode.com/posts/"
          :headers="{'Authorization':'Bearer '+ token}"
          :on-success="(res,file)=>{uploadSuccess(item,res,file)}"
          :show-file-list="false"
          :limit="1"
          class="avatar-uploader"
          style="margin-left:10px"
          >
            <img v-if="item.img" :src="item.img" class="avatar">
              <span v-else>上传图片</span>
              <i class="el-icon-circle-close"></i>
          </el-upload>
         </div>
         <el-button :disabled="allForm.questionType!=='2'" @click="addOption" type="danger" size="small">+增加选项与答案</el-button>
        </el-form-item>
        <!--10、 解析视频 -->
        <el-form-item label="解析视频:" label-width="90px">
          <el-input v-model="allForm.videos" style="width:45%"></el-input>
        </el-form-item>
         <!--11、 答案解析-富文本框 -->
        <el-form-item label="答案解析:" prop="question" label-width="90px">
           <quill-editor v-model="allForm.answerMain" :options="editorOptions"></quill-editor>
        </el-form-item>
        <!--12、 题目备注 -->
        <el-form-item label="题目备注:" label-width="90px">
        <el-input type="textarea" style="width:45%;min-height:33px;" rows="4" v-model="allForm.marked" autocomplete="off"></el-input>
        </el-form-item>
        <!--13、 试题标签 -->
        <el-form-item label="试题标签:" label-width="90px">
           <el-select
           v-model="allForm.tags"
           multiple
           filterable
           allow-create
           default-first-option
           placeholder="请选择"
           style="width:45%">
          <el-option
            v-for="item in tagsOptions"
            :key="item.value"
            :label="item.label"
            :value="item.label">
          </el-option>
        </el-select>
        </el-form-item>
        <!--14、 提交按钮 -->
        <el-button v-if="!$route.query.id" @click="submit()" type="primary" style="margin-left:80px">确认提交</el-button>
        <el-button v-else @click="update()" type="success" style="margin-left:80px">确认修改</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

import hljs from 'highlight.js'
import 'highlight.js/styles/vs2015.css'

import { simple as subjectsList } from '@/api/hmmm/subjects'
import { simple as directorysList } from '@/api/hmmm/directorys'
import { simple as getTagOptions } from '@/api/hmmm/tags'
import { list as companysList } from '@/api/hmmm/companys'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
//
import { provinces, citys as getAreaOptions } from '@/api/hmmm/citys'
import { add, detail, update } from '@/api/hmmm/questions'
import { getToken } from '@/utils/auth'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      token: getToken(),
      editorOptions: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ],
          // 语法高亮
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      },
      radio: '1',
      // 学科
      subjectsOptions: [],
      // 目录
      directorysOptions: [],
      // 企业
      companysOptions: [],
      // 方向
      directionOptions: direction,
      // 省
      provincesOptions: provinces(),
      // 市
      areaOptions: [],
      // 题型
      questionType,
      // 难度
      difficulty,
      // 标签
      tagsOptions: [],
      allForm: {
        subjectID: '',
        creatorID: '',
        id: '',
        direction: '',
        provinces: '',
        city: '',
        questionType: '1',
        difficulty: '1',
        question: '',
        // 选项
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ]
      },
      // 校验规则
      allRules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        creatorID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        id: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ]
      }
    }
  },
  async created () {
    // 学科
    this.getSubjectsList()
    // 目录
    this.getDirectorysList()
    // 企业
    this.getCompanysList()
    //  题目信息
    if (this.$route.query.id) {
      this.getQuestion()
    }
  },
  watch: {
    '$route.query': function () {
      //
      if (this.$route.query.id) {
        this.getQuestion()
      } else {
        this.allForm = {
          subjectID: '',
          creatorID: '',
          id: '',
          direction: '',
          provinces: '',
          city: '',
          questionType: '1',
          difficulty: '1',
          question: '',
          // 选项
          options: [
            { isRight: false, code: 'A', title: '', img: '' },
            { isRight: false, code: 'B', title: '', img: '' },
            { isRight: false, code: 'C', title: '', img: '' },
            { isRight: false, code: 'D', title: '', img: '' }
          ]
        }
        this.$nextTick(() => {
          this.$refs.form.clearValidate()
        })
      }
    }
  },
  methods: {
    // 获取题目信息
    async getQuestion () {
      // this.$route.query.id
      const { data } = await detail({ id: this.$route.query.id })
      // console.log(data)
      data.tags = data.tags.split(',')
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })
      this.allForm = data
      const res = await directorysList({ subjectID: this.allForm.subjectID })
      this.directorysOptions = res.data
      const res2 = await getTagOptions({ subjectID: this.allForm.subjectID })
      this.tagsOptions = res2.data
      // 滚动顶部
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      })
    },
    // 改变学科
    async changeSubject (subjectID) {
      this.allForm.creatorID = null
      const res = await directorysList({ subjectID: this.allForm.subjectID })
      this.directorysOptions = res.data
      this.allForm.tags = null
      const res2 = await getTagOptions({ subjectID: this.allForm.subjectID })
      this.tagsOptions = res2.data
    },
    // 提交
    submit () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const data = { ...this.allForm }
          console.log(data)
          data.tags = data.tags.join(',')
          console.log(data.tags)
          await add(data)
          this.$message.success('添加成功')
          this.$router.push('/questions/list')
        }
      })
    },
    update () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          const data = { ...this.allForm }
          data.tags = data.tags.join(',')
          await update(data)
          this.$message.success('修改成功')
          this.$router.push('/questions/list')
        }
      })
    },
    uploadSuccess (item, res, file) {
      item.img = URL.createObjectURL(file.raw)
    },
    // 添加选项
    addOption () {
      this.allForm.options.push({
        isRight: false,
        code: String.fromCharCode(65 + this.allForm.options.length),
        title: '',
        img: ''
      })
    },
    changeRadio (item) {
      this.allForm.options.forEach(item => {
        item.isRight = false
      })
      item.isRight = true
    },
    // 校验题干
    checkQustion () {
      this.$refs.form.validateField('question')
    },
    // 学科渲染
    async getSubjectsList () {
      const res = await subjectsList()
      this.subjectsOptions = res.data
    },
    // 目录
    async getDirectorysList () {
      const res = await directorysList()
      // console.log(res)
      this.directorysOptions = res.data
    },
    // 企业
    async getCompanysList () {
      const res = await companysList({ pagesize: 10000 })
      // console.log(res.data.items, '1111111111111')
      this.companysOptions = res.data.items
    },
    getAreaOptions (cityName) {
      // 清空  地区选中的值
      this.allForm.city = ''
      // cityName 是你选中城市后的值
      this.areaOptions = getAreaOptions(cityName)
    }

  }
}
</script>

<style scoped lang='less'>
.headerErea{
border-bottom: 1px solid #ebeef5;
}
.option_item{
  display: flex;
  // position: relative;
   padding-bottom: 20px;
}
// .avatar {
//   width: 100px;
//   height: 60px;
//   display: block;
//   overflow: hidden;
// }

::v-deep{

  .el-card{
    margin-left: 18px;
    margin-right: 18px;
  }
// 富文本内容高度
  .ql-container {
    min-height: 200px;
  }
  .avatar-uploader{
  display: inline-block;
  vertical-align: middle;
  line-height: 1;
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    width: 100px;
    height: 60px;
    line-height: 60px;
    img{
        width: 100px;
        height: 60px;
    }
  }
  .el-upload:hover {
    border-color: #409EFF;
  }
  i{
  position: absolute;
  right: 0;
  top: 0;
  transform: translate(50%,-50%);
  background: #fff;
  font-size: 18px;
  color: #999;
  }
}
}

</style>
